package com.example.config.simpleDynamicTask2;

import com.example.config.simpleDynamicTask2.job.TaskWillOverDueCheckTask;
import com.example.config.simpleDynamicTask2.mapper.SpringScheduledCronMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 已废弃: 难以做到前端在配置页面修改数据库cron表达式时动态修改定时任务
 * 启动时根据数据库创建系统定时任务
 *
 * @author ZhengDing
 * @date 2022/3/30 23:03
 */
@Configuration
// @AutoConfigureAfter({
//         MybatisPlusAutoConfiguration.class,
//         MybatisPlusLanguageDriverAutoConfiguration.class,
//         TaskWillOverDueCheckTask.class
// })
@Slf4j
@ConditionalOnExpression("false")
public class TaskCheckScheduledConfig implements SchedulingConfigurer {
    
    // configuration 中只能使用 mapper 和 自定义 sql 语句; 使用 service 会导致启动失败
    @Autowired
    SpringScheduledCronMapper cronMapper;
    
    @Autowired
    TaskWillOverDueCheckTask task;
    
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(task, triggerContext -> {
            //查询数据库  获得 TaskWillOverDueCheckTask 任务 的cron表达式
            // String cronExpression = "0/10 * * * * ?";
            // String cronExpression = cronService.getCronExpressionByKey(TaskWillOverDueCheckTask.class.getName());
            String cronExpression = cronMapper.getCronExpressionByKey(TaskWillOverDueCheckTask.class.getName());
            log.info("find cron for TaskWillOverDueCheckTask: " + cronExpression);
            Date executionTime = new CronTrigger(cronExpression).nextExecutionTime(triggerContext);
            return executionTime;
        });
        
    }
    
    @Bean
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(16);
    }
}
